// components/image-uploader/index.js
import config from '../../utils/config.js'
import { ImageItem } from './image-item.js'
import { Target, Toast } from '../../utils/http_util.js'

const defaultAddIcon = config.ictx  + 'ef41d997aada74ce3be579c111334e19'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    id: String,
    title: String,
    showTitle: {
      type: Boolean,
      value: true
    },
    min: {
      type: Number,
      value: 1
    },
    max: {
      type: Number,
      value: 1
    },
    //min > 0 || required 视为必传title 红*
    required: {
      type: Boolean,
      value: true
    },
    editable: {
      type: Boolean,
      value: true
    },
    mode: {
      type: String,
      value: 'muti'//muti, single
    },
    pickMode: {
      type: String,
      value: 'all'//all, camera, photo
    },
    imageTitleClass:{
      type: String,
      value: ''
    },
    addBtnUrl: {
      type: String,
      value: defaultAddIcon,
      observer: function (newVal, oldVal, changedPath) {
        let imageList = this.data.imageList
        imageList[imageList.length - 1].imageData = newVal
      }
    },
    //'SF': 同时后台调集团证件上传接口
    process: {
      type: String,
      observer: function (newVal, oldVal, changedPath) {
        let imageList = this.data.imageList
        imageList.map(item => {
          item.process = newVal
        })
      }
    },
    //'SF': 同时后台调集团证件上传接口 资质图片类型 企业进件 process=SF_BUSI
    aptitudeType: {
      type: String,
      observer: function (newVal, oldVal, changedPath) {
        let imageList = this.data.imageList
        imageList.map(item => {
          item.aptitudeType = newVal
        })
      }
    },
    initImageList: {
      type: String,//json string
      observer: function (newVal, oldVal, changedPath) {

        if(newVal == undefined || newVal == '') {
          this.setData({
            imageList: []
          })
          return
        }
        newVal = JSON.parse(newVal)
        if(newVal.length) {
          const items = []
          newVal.map(item => {
            items.push(new ImageItem(item, '', false, this.data.process, this.data.aptitudeType))
          })
          if (this.data.mode == 'muti' && items.length < this.data.max && this.data.editable) {
            items.push(new ImageItem(defaultAddIcon, '', true, this.data.process, this.data.aptitudeType))
          }
          this.setData({
            imageList: items
          })
        }
      }
    },
    itemClass: String,

  },

  /**
   * 组件的初始数据
   */
  data: {
    defaultAddIcon: defaultAddIcon,
    imageList: [new ImageItem(defaultAddIcon, '', true)]
  },

  /**
   * 组件的方法列表
   */
  methods: {
    _chooseImage(e) {
      const self = this
      const id = e.currentTarget.dataset.imageItemId
      const sourcetype = self.data.pickMode
      var source = []
      if(!typeof(sourcetype)==''){
        if (sourcetype == 'album' || sourcetype == 'camera'){
          source.push(sourcetype);
        }else{
          source = ['album', 'camera']
        }
      }else{
        source = ['album', 'camera']
      }
      wx.chooseImage({
        sizeType: ['compressed'],
        count: 1,
        sourceType:source,
        success: function (res) {
          const imageItem = self._getImageItem(id)
          imageItem.imageData = res.tempFilePaths[0]
          imageItem.status = 'ready'
          imageItem.checkUpload((item, res) => {
            self.setData({
              imageList: self.data.imageList
            })
            if(res) {
              console.log('上传进度', res.progress, 
              ';已上传', res.totalBytesSent,
              ';总长度', res.totalBytesExpectedToSend)
            }
          })

          if(self.data.mode == 'muti' && self.data.imageList.length < self.data.max) {
            self.data.imageList.push(new ImageItem(defaultAddIcon, '', true, self.data.process, self.data.aptitudeType))
          }

          self.setData({
            imageList: self.data.imageList
          })
        },
      })
    },

    _previewImage(e) {
      const id = e.currentTarget.dataset.imageItemId
      const imageItem = this._getImageItem(id)
      const url = this._getImageUrl(imageItem)

      wx.previewImage({
        urls: this._getImageUrlList(),
        current: url,
      })
    },

    _getImageUrlList() {
      const images = []
      const imageList = this.data.imageList
      imageList.map((item, index) => {
        if (!item.isPlusBtn) {
          images.push(this._getImageUrl(item))
        }
      })
      return images
    },

    _getImageUrl(item) {
      item = item.imageData
      if (!item || item == '') {
        return ''
      }
      if (typeof item == 'string') {
        return item
      }
      return item.downloadUrl
    },

    _deleteImage(e) {
      const id = e.currentTarget.dataset.imageItemId
      const imageList = this.data.imageList
      imageList.map((item, index) => {
        if(item.id == id) {
          imageList.splice(index, 1)
        }
      })
      //判断多个图片达到上限后删除后新增加号按钮
      const last = imageList[imageList.length - 1]
      if (last == undefined || (this.data.mode == 'muti' && imageList.length < this.data.max && !last.isPlusBtn)) {
        imageList.push(new ImageItem(defaultAddIcon, '', true))
      }

      this.setData({
        imageList: imageList
      })
    },

    _getImageItem(id) {
      let imageList = this.data.imageList
      return imageList.find((value, index, array) => {
        return value.id == id
      })
    },

    getImageListData() {
      for (let i in this.data.imageList) {
        let item = this.data.imageList[i]
        if (item.status == 'uploading') {
          Toast.message('有图片正在上传中，请等待')
          throw new Error('有图片正在上传中，请等待')
        }
      }
      let list = []
      this.data.imageList.map(item => {
        if ((item.status == 'success' || item.status == '') && !item.isPlusBtn) {
          list.push(item.imageData)
        }
      })
      return JSON.stringify(list)
    },
    /**
     * 符合约束条件返回`undefined`,否则返回提示内容,暂未使用
     */
    checkValid() {
      let list = this.getImageListData()
      let error
      for(let item in list) {
        if (['ready', 'uploading'].indexOf(item.status)) {
          error = `请等待${this.data.title}上传完成`
          break
        }
        if(item.status == 'fail') {
          error = `]${this.data.title}上传失败，请重试`
          break
        }
      }

      if(error) {
        return error
      }
    
      if(this.data.required || this.data.min) {
        if(!list.length) {
          return `请上传${this.data.title}`
        }
        if(list.length < this.data.min) {
          return `请上传至少${this.data.min}张${this.data.title}`
        }
      }
    }
  },
})


